package cn.bluemobi.dylan.step.ui.main.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bluemobi.dylan.step.R;
import cn.bluemobi.dylan.step.activity.HistoryActivity;
import cn.bluemobi.dylan.step.activity.SetPlanActivity;
import cn.bluemobi.dylan.step.base.BaseMvpFragment;
import cn.bluemobi.dylan.step.moder.bean.StepData;
import cn.bluemobi.dylan.step.moder.bean.User;
import cn.bluemobi.dylan.step.presenter.contract.WelcomeContract;
import cn.bluemobi.dylan.step.presenter.contract.main.MainContract;
import cn.bluemobi.dylan.step.presenter.main.MainPresenter;
import cn.bluemobi.dylan.step.step.UpdateUiCallBack;
import cn.bluemobi.dylan.step.step.service.StepService;
import cn.bluemobi.dylan.step.step.utils.SharedPreferencesUtils;
import cn.bluemobi.dylan.step.utils.common.LogUtils;
import cn.bluemobi.dylan.step.view.StepArcView;

/**
 * Created by $Liudan on 2018/11/21 0021.
 */
public class MainFragment extends BaseMvpFragment<MainPresenter> implements MainContract.View{

    @BindView(R.id.tv_data)
    TextView tv_data;
    @BindView(R.id.cc)
    StepArcView cc;
    @BindView(R.id.tv_set)
    TextView tv_set;
    @BindView(R.id.tv_isSupport)
    TextView tv_isSupport;
    @BindView(R.id.tv_stepcount)
    TextView tv_stepcount;

    private SharedPreferencesUtils sp;
    int dbStepcount;  //本地今日步数
    int httpStepcount; //服务器今日步数

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.main;
    }

    @Override
    protected void initEventAndData() {
        initData();
    }

    private void initData() {
        sp = new SharedPreferencesUtils(getActivity());
        //获取用户设置的计划锻炼步数，没有设置过的话默认7000
        String planWalk_QTY = (String) sp.getParam("planWalk_QTY", "7000");
        //设置当前步数为0
        cc.setCurrentCount(Integer.parseInt(planWalk_QTY), 0);
        tv_isSupport.setText("计步中...");

        mPresenter.dbUplodStepcountList();
        mPresenter.dbTodayStepcount();
        mPresenter.preUser();
//        setupService();

    }

    private void setStepcount(int stepcount){
        tv_stepcount.setText(stepcount+"步");
    }

    private boolean isBind = false;
    /**
     * 开启计步服务
     */
    private void setupService() {
        Intent intent = new Intent(getActivity(), StepService.class);
        isBind = getActivity().bindService(intent, conn, Context.BIND_AUTO_CREATE);
        getActivity().startService(intent);
    }

    @OnClick({R.id.tv_set,R.id.tv_data})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.tv_set:
                startActivity(new Intent(getActivity(), SetPlanActivity.class));
                break;
                case R.id.tv_data:
                    startActivity(new Intent(getActivity(), HistoryActivity.class));
                break;
        }
    }

    /**
     * 用于查询应用服务（application Service）的状态的一种interface，
     * 更详细的信息可以参考Service 和 context.bindService()中的描述，
     * 和许多来自系统的回调方式一样，ServiceConnection的方法都是进程的主线程中调用的。
     */
    ServiceConnection conn = new ServiceConnection() {
        /**
         * 在建立起于Service的连接时会调用该方法，目前Android是通过IBind机制实现与服务的连接。
         * @param name 实际所连接到的Service组件名称
         * @param service 服务的通信信道的IBind，可以通过Service访问对应服务
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            StepService stepService = ((StepService.StepBinder) service).getService();
            //设置初始化数据
            String planWalk_QTY = (String) sp.getParam("planWalk_QTY", "7000");
            cc.setCurrentCount(Integer.parseInt(planWalk_QTY), stepService.getStepCount());

            //设置步数监听回调
            stepService.registerCallback(new UpdateUiCallBack() {
                @Override
                public void updateUi(int stepCount) {
                    LogUtils.debug(this.getClass().getName(),"111111111111111111111111111stepCount======="+stepCount);
                    String planWalk_QTY = (String) sp.getParam("planWalk_QTY", "7000");
                    cc.setCurrentCount(Integer.parseInt(planWalk_QTY), stepCount);
                    setStepcount(stepCount);
                }
            });
        }

        /**
         * 当与Service之间的连接丢失的时候会调用该方法，
         * 这种情况经常发生在Service所在的进程崩溃或者被Kill的时候调用，
         * 此方法不会移除与Service的连接，当服务重新启动的时候仍然会调用 onServiceConnected()。
         * @param name 丢失连接的组件名称
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };



    @Override
    public void showError(String msg) {

    }

    @Override
    public void stateError() {

    }

    @Override
    public void showDialog() {

    }

    @Override
    public void closeDialog() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isBind) {
            getActivity().unbindService(conn);
        }
    }

    @Override
    public void prefUserSuccess(User user) {
        mPresenter.todayStep(user.memberId);
    }

    @Override
    public void showStepcount(StepData stepData) {  //本地数据库获取今日步数
        LogUtils.debug(this.getClass().getName(),"11111111111111111stepData==步数=="+stepData.getStepNumber());
        if(stepData!=null){
            dbStepcount = stepData.getStepNumber();
            if(dbStepcount>httpStepcount){
                setStepcount(dbStepcount);
            }else {
                setStepcount(httpStepcount);
            }
        }
    }

    @Override
    public void httpSuccess() {

    }

    @Override
    public void httpFail() {

    }

    @Override
    public void httpStepCountSuccess(StepData mStep) { //服务器获取今日步数
        if(getActivity().isFinishing())return;
        httpStepcount = mStep.getStepNumber();
        if(httpStepcount>dbStepcount){
            setStepcount(httpStepcount);
            mPresenter.dbSaveTodyStepCount(mStep);
        }else {
            setStepcount(dbStepcount);
        }
    }

    @Override
    public void startStepService() {  //服务器获取今日步数后  开启计步service
        setupService();
    }
}
